package org.logistics.tools;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 
 * @author L_G-TIM
 *作为回放轨迹Activity的子线程，主要负责请求接口的轨迹点数据
 */
public class RequestToHistoryThread extends Thread {
	
	private static final String TAG = "RequestToHistoryThread";

	Handler uihandler = null;
	String stDateTime = null;
	String enDateTime = null;
	String IMEI = null;
	//Handler wifehandler;
	/**
	 * 请求历史轨迹接口后，取得的轨迹点
	 */
	private JSONArray rootResults = null;
	/**
	 * handler Message.what
	 * 线程消息what
	 */
	private final int REPLAY = 1;

	/**
	 * 带三个参数的构造函数
	 */
	public RequestToHistoryThread(Handler handler, String IMEI, String stDateTime,
			String enDateTime) {
		this.uihandler = handler; // 利用构造函数接受主线程的handler，由于是内部类，其实直接用主线程的handler也可以。
		this.IMEI = IMEI;
		this.stDateTime = stDateTime;
		this.enDateTime = enDateTime;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		Log.d(TAG, "in the runMethod "+  Thread.currentThread().getName());
		requestReplayPath(IMEI, stDateTime, enDateTime, null, null);
	//	JSONArray ja = null;
		if(rootResults != null)
		{
/*			try {
				Log.d(TAG, "sleep");
				Thread.sleep(10000);
				Log.d(TAG, "awake");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} */ 
			Message msg = uihandler.obtainMessage(REPLAY, rootResults);
			uihandler.sendMessage(msg);
		}
	}

	/**
	 * 请求接口，返回历史轨迹点的数据
	 * 
	 * @param IMEI
	 * @param stDateTime
	 * @param enDateTime
	 * @param mapType
	 * @param url
	 */
	public void requestReplayPath(String IMEI, String stDateTime,
			String enDateTime, String mapType, String url) {

	//	stDateTime = "2013-11-30 00:00:00";
	//	enDateTime = "2013-11-30 11:00:00";
	//	IMEI = "356823033198479"; // IMEI
		mapType = "baidu";

		String requestUrl = null;
		requestUrl = "http://sj.jy100.com"
				+ "/JKSJ-HistoryDomainService.svc/JSON/GetHistoryGpsData"
				+ "?sn=" + IMEI + "&startTime=" + stDateTime + "&endTime="
				+ enDateTime + "&map=" + mapType;
		// url中含有空格等，转义符解决
		requestUrl = requestUrl.replace(" ", "%20");
		Log.d(TAG, "data ready" + requestUrl);

		try {
			HttpClient replayClient = new DefaultHttpClient();
			HttpGet getRequest = new HttpGet(requestUrl);

			HttpResponse response = replayClient.execute(getRequest);
			Log.d(TAG, response.getStatusLine().getStatusCode() + "");
			/**
			 * 校验loginClient访问URL的返回状态， 状态为HttpStatus.SC_OK，即URL访问成功
			 */
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				Log.d(TAG, "replay request finish?? ");
				// 得到应答的字符串，这个是一个Json格式保存的数据
				String replayResult = EntityUtils.toString(response
						.getEntity());

				if (replayResult != null && !replayResult.trim().equals("")) {
					JSONObject resultJO = new JSONObject(replayResult);

					rootResults = resultJO.getJSONObject(
							"GetHistoryGpsDataResult").getJSONArray(
							"RootResults");
					Log.d(TAG, "in the requestReplayPath "+  Thread.currentThread().getName());
				} else {
					Log.d(TAG, "no path return");
				}
			} else {
				Log.d(TAG, "Login Error");
			}// end check HttpStatus
		} catch (ClientProtocolException ce) {
			Log.d(TAG, ce.getMessage().toString());
			ce.printStackTrace();
		} catch (JSONException je) {
			je.printStackTrace();
			System.out.println(je.toString());
			Log.d(TAG,
					"ReplayResult JSONException, no such mapping exists ");
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

}